package zsc.ruanc.practicaltraining.security.handler;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import zsc.ruanc.practicaltraining.mapper.Redis;
import zsc.ruanc.practicaltraining.mapper.UserMapper;
import zsc.ruanc.practicaltraining.model.domain.TUser;
import zsc.ruanc.practicaltraining.model.result.JsonResult;
import zsc.ruanc.practicaltraining.security.auth.AuthUser;
import zsc.ruanc.practicaltraining.service.UserService;
import zsc.ruanc.practicaltraining.utils.ResultUtils;
import zsc.ruanc.practicaltraining.utils.TokenUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *  登录成功
 */
@Component
public class SAuthenticationSuccessHandler extends JSONResult implements AuthenticationSuccessHandler {

    @Autowired
    private Redis redis;

    @Autowired
    private UserMapper userMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //取得账号信息
        AuthUser user = (AuthUser) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //



        String role = user.getRole();

        String key = TokenUtils.randomKey();

        String token = TokenUtils.create(user.getId(), role, user.getUsername(), key);

        redis.set(String.valueOf(user.getId()), key, 3600);

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);

        JsonResult data = ResultUtils.success(map);

        this.WriteJson(httpServletRequest, httpServletResponse, data);

    }
}
